/**
 * 功能描述
 */

define(function (require, exports, module) {
	var aw = require("ajaxwrapper");
	var Dialog = require("dialog");
	var getSignupCharge = require("../store/getSignupCharge");
	var settleData = require("../constant/settleData");
	var total = require("./total");
    module.exports = {
		grid: {
			handlerSettleClick: function(widget, data) {
				if(data.statementStatus && data.statementStatus.key == "Statement") {
					Dialog.alert({
						content: "该记录已结算！"
					});
					return;
				}
					
				var form = widget.get("form");
				var endGrid = widget.get("endGrid");
				var liveDays = (moment(data.groupReserve.checkOutDate).startOf("day").valueOf() - 
						moment(data.groupReserve.checkInDate).startOf("day").valueOf())/1000/60/60/24;
				widget.set("pkGroupReserve",data.groupReserve.pkGroupReserve);
				form.reset();
				form.setData({
					startDate: data.groupReserve.planItemGroup.planItem.startDate,
					destination: data.groupReserve.planItemGroup.planItem.destination.pkDestination,
					destinationName: data.groupReserve.planItemGroup.planItem.destination.name,
					checkInDate: data.groupReserve.checkInDate,
					checkOutDate: data.groupReserve.checkOutDate,
					signUpNum: data.signUpNum,
					statementDate: data.statementDate,
					user: data.groupReserve.operator.operator.pkUser,
					liveDays: liveDays
				});
				
				endGrid.setData([]);
				
				$.each(data.roomPersonalInfos,function(i,n){
					n.checkOutSettlement.sum += n.damagesConsumption + n.roomConsumption;
					n.checkOutSettlement.balance = n.checkOutSettlement.sum
					- n.checkOutSettlement.bedSubsidy
					- n.checkOutSettlement.coupon
					- n.checkOutSettlement.expense;
					n.liveDays = liveDays;
					n.disabled = true;
				});
				//查询预收款
				getSignupCharge(data.roomPersonalInfos,function(tdata){
					widget.set("endGridData",tdata);
					endGrid.setData(tdata);
					total.total(widget,tdata,data);
				});
				
				widget.show([".J-form",".J-endGrid",".J-total"]).hide([".J-grid",".J-detailForm"]);
				widget.get("subnav").show(["return","save"]).hide(["statementStatus","alliance","servicePoint","destination", "time"]);
			},
			handlerDetailClick: function(widget,data){
				
				var form = widget.get("form");
				var endGrid = widget.get("endGrid");
				var liveDays = (moment(data.groupReserve.checkOutDate).startOf("day").valueOf() - 
						moment(data.groupReserve.checkInDate).startOf("day").valueOf())/1000/60/60/24;
				widget.set("pkGroupReserve",data.groupReserve.pkGroupReserve);
				form.reset();
				form.setData({
					startDate: data.groupReserve.planItemGroup.planItem.startDate,
					destination: data.groupReserve.planItemGroup.planItem.destination.pkDestination,
					destinationName: data.groupReserve.planItemGroup.planItem.destination.name,
					checkInDate: data.groupReserve.checkInDate,
					checkOutDate: data.groupReserve.checkOutDate,
					signUpNum: data.signUpNum,
					statementDate: data.statementDate,
					user: data.groupReserve.operator.operator.pkUser,
					liveDays: liveDays
				});
				
				endGrid.setData([]);
				
				for(var i=0;i<data.paymentMethods.length;i++){
					if(data.paymentMethods[i].key=="OnCredit"){
						var onCreditForm = widget.get("onCreditForm");
						onCreditForm.setValue("company",data.company);
						onCreditForm.setValue("perName",data.perName);
						onCreditForm.setValue("phone",data.phone);
						onCreditForm.setValue("onCreditMoney",data.onCreditMoney);
						onCreditForm.setDisabled(true);
						widget.show([".J-onCreditForm"]);
						break;
					}
				};
				$.each(data.roomPersonalInfos,function(i,n){
					n.checkOutSettlement.sum += n.damagesConsumption + n.roomConsumption;
					n.checkOutSettlement.balance = n.checkOutSettlement.sum
					- n.checkOutSettlement.bedSubsidy
					- n.checkOutSettlement.coupon
					- n.checkOutSettlement.expense;
					n.liveDays = liveDays;
					n.disabled = true;
				});
				//查询预收款
				getSignupCharge(data.roomPersonalInfos,function(tdata){
					widget.set("endGridData",tdata);
					endGrid.setData(tdata);
					total.total(widget,tdata,data);
				});
				form.setDisabled(true);
				widget.get("totalGrid").setDisabled(true);
				widget.show([".J-form",".J-endGrid",".J-total"]).hide([".J-grid","J-detailForm"]);
				widget.get("subnav").show(["return","totalprint"]).hide(["paymentMethod","statementStatus","alliance","servicePoint","destination", "time","save"]);
			},
		},
		endGrid: {
			settle:function(widget,data,index,disabled){
				widget.set("cGridData",data);
				
			var detailForm = widget.get("detailForm"),
				electric = data.checkOutSettlement.electric ? data.checkOutSettlement.electric : 0,
				food = data.checkOutSettlement.food ? data.checkOutSettlement.food : 0,
				coupon = data.checkOutSettlement.coupon ? data.checkOutSettlement.coupon :0,
				expense = data.checkOutSettlement.expense ? data.checkOutSettlement.expense:0,
				bedSubsidy = data.checkOutSettlement.bedSubsidy ?data.checkOutSettlement.bedSubsidy:0,
				room = data.checkOutSettlement.room ? data.checkOutSettlement.room :0,
				bedSubsidyUnit = data.checkOutSettlement.bedSubsidyUnit;
				
				detailForm.reset();
				detailForm.setValue("index",index);
				detailForm.setData(data.checkOutSettlement);
				detailForm.setValue("name", data.signUpRegister.personalInfo.name);
				detailForm.setValue("idNumber", data.signUpRegister.personalInfo.idNumber);
				detailForm.setValue("liveDays", data.liveDays);
				detailForm.setValue("roomCode", data.roomRegister.room.code);
				detailForm.setValue("roomType", data.roomRegister.room.roomType.name);
				detailForm.setValue("checkInDate", widget.get("form").getValue("checkInDate"));
				detailForm.setValue("checkOutDate", widget.get("form").getValue("checkOutDate"));
				if(data.signUpRegister.travelContract){
					detailForm.setValue("contractNumber", data.signUpRegister.travelContract.productRule.product.name + "-"
							+ data.signUpRegister.travelContract.memberCertificates);
				}
				if(bedSubsidyUnit){
					detailForm.setValue("bedSubsidyUnit",bedSubsidyUnit);
				}
				detailForm.setDisabled(true);
			
				widget.show([".J-detailForm"]).hide([".J-form",".J-endGrid",".J-total",".J-grid"]);
				if(!disabled){
					widget.get("subnav").show(["print"]).hide(["paymentMethod","statementStatus","return","save","alliance","servicePoint","destination", "time"]);
				}else{
					widget.get("subnav").show(["print"]).hide(["return","totalprint"]);
				}
				
				$(".J-detailForm .J-grid-total-info").hide();
				widget.get("settleEditGridOne").setData(settleData.settleDataOne(data,widget,disabled));
				widget.get("settleEditGridTwo").setData(settleData.settleDataTwo(data,widget,disabled));
			}
		},
		detailForm:{
			exValidate:function(value,name,form){},
			calculate:function(widget,value,name){},
			saveaction:function(widget){
				var detailForm = widget.get("detailForm"),
					data = detailForm.getData(),
					index = data.index,
					endGrid = widget.get("endGrid"),
					cGridData = widget.get("cGridData");
				
				data.checkOutSettlement = true;
				//data中填充值
				$(".J-detailForm span").each(function(){
					data[$(this).attr("id")] = parseFloat($(this).text());
                });
				$(".J-detailForm input").each(function(){
					data[$(this).attr("id")] = parseFloat($(this).val());
                });
				
				cGridData.checkOutSettlement = data;
				var endData = endGrid.getData();
				for(var k = 0; k < endData.length; k++){
					if(endData[k].checkOutSettlement.pkCheckOutSettlement == cGridData.checkOutSettlement.pkCheckOutSettlement){
						endData[k].checkOutSettlement = cGridData.checkOutSettlement;
						break;
					}
				}
				endGrid.setData(endData);
				var endGridData = widget.get("endGridData");
				
				//计算总和
				var dats = [];
				var returnView = {};
				var roomTotal = 0; //住宿费合计
				var foodTotal = 0; //餐饮费合计
				var trafficTotal = 0; //大交通往返费合计
				var otherTotal = 0; //其他费用合计
				var allTotal = 0; //费用总金额
				var depositTotal = 0; //预收款合计
				var deductionChargesTotal = 0; //权证抵扣合计
				var receivableTotal = 0;//应收金额合计
				var receiptsTotal = 0;//实收金额合计
				var bedSubsidyUnit= data.bedSubsidyUnit;
				for(var i=0;i<endGridData.length;i++){
					var items = endGridData[i].checkOutSettlement;
					var remak = items.remak;
					var bedSubsidyUnit = items.bedSubsidyUnit;
					for(var k in items){
						if(items[k]){
							items[k] = Number(items[k])
						}else{
							items[k] = 0
						}
					}
					items.remak = remak;
					items.bedSubsidyUnit = bedSubsidyUnit;
				}
				for(var m=0;m<endGridData.length;m++){
					var cItem =  endGridData[m].checkOutSettlement;
					if(cItem){
						roomTotal += cItem.room;
						trafficTotal += cItem.traffic;
						//其他费用合计=∑水费+水费其他+电费+电费其他+康乐费+康乐费其他+护理费+物业费+节假日费用+接送往返费+管理费+其他 ；
						otherTotal += cItem.coldWater + cItem.hotWater + cItem.telephone + cItem.waterOther
							+ cItem.electric +  cItem.electricOther + endGridData[m].damagesConsumption + endGridData[m].roomConsumption
							+ cItem.health + cItem.healthOther + cItem.nurse + cItem.property + cItem.holiday
							+ cItem.pickUp + cItem.manager + cItem.other + cItem.food;
						
						if(endGridData[m].payable){
							depositTotal += endGridData[m].payable;
						}
						deductionChargesTotal += cItem.bedSubsidy + cItem.expense + cItem.coupon;
					}
				}
				allTotal = roomTotal + trafficTotal + otherTotal;
				receivableTotal = allTotal - deductionChargesTotal - depositTotal;
				returnView.roomTotal = roomTotal;
				returnView.trafficTotal = trafficTotal;
				returnView.otherTotal = otherTotal;
				returnView.allTotal = allTotal;//费用总金额
				returnView.depositTotal = depositTotal;//预收款合计
				returnView.deductionChargesTotal = deductionChargesTotal;//权证抵扣合计
				returnView.receivableTotal = receivableTotal//应收金额合计
				
				var balance = widget.get("receiptsTotal");
				var paymentMethod = widget.get("paymentMethod");
				var description = widget.get("description");
				if(balance == null){
					returnView.receiptsTotal = receivableTotal;//实收金额合计
				}else{
					returnView.receiptsTotal = balance;
				}
				if(paymentMethod!=null){
					returnView.paymentMethod=paymentMethod;
				}else{
					returnView.paymentMethod=[{key:"Cash",value:"现金"}];
				}
				if(description != "" ){
					returnView.description = description;
				}
				dats.push(returnView);
				widget.get("totalGrid").setData([]);
				widget.get("totalGrid").setData(dats);
			},
			settleEvents :function(e){
				var targetValue = e.target.value;
				var reg = /[^\- \d.]/g ;
				if(!reg.test(targetValue)){
          			$("#" + e.target.id + "").val(parseFloat(targetValue).toFixed(2));
				} else{
	      			 Dialog.alert({
	      				 tip : "提示",
	      				 content : "金额必须输入数字且不能为负！"
	      			 });
	      			 $("#" + e.target.id + "").val(parseFloat(0).toFixed(2));
	      			 return false;
				}
				var sum = 0;	// 费用合计
				$(".J-detailForm #settleEditGridOne span").each(function(){
					if($(this).attr("id") != "sum"){
						sum += parseFloat($(this).text());
					}
                });
				$(".J-detailForm #settleEditGridOne input").each(function(){
					if($(this).attr("id") != "sum"){
						sum += parseFloat($(this).val());
					}
                });
				$(".J-detailForm #sum").text(parseFloat(sum).toFixed(2));
				var deduction = 0; // 抵扣合计
				$(".J-detailForm #settleEditGridTwo span").each(function(){
					if($(this).attr("id") != "balance"){
						deduction += parseFloat($(this).text());
					}
                });
				$(".J-detailForm #settleEditGridTwo input").each(function(){
					if($(this).attr("id") != "balance"){
						deduction += parseFloat($(this).val());
					}
                });
				var balance = sum-deduction;
				$(".J-detailForm #balance").text(parseFloat(balance).toFixed(2));
			}
		},
		
		setSettleData:function(data){
			
		},
		
		print: function(widget){
			window.open("assets/settleprint.html?"+settleData.printData(widget)+"");
		}
    };
});
